/// <reference path="../jquery/jquery.d.ts" />
// 数学练习JS
"use strict";

// 题目列表
var questionList = [];
// 开始时间
var startTime = null;
// 当前题目
var questionIndex = 0;
var difficulty = 10;
var questionNumber = 0;

var success = 0;
var errors = 0;
var calculated = 0;

$(function() {
    // 初始化
    init();

    // 获取本地文件  jquery.cookie插件 学习地址: https://www.runoob.com/jquery/jquery-cookie-plugin.html

    // 计算题目

});

// 数字键 退格键
$("#number1").click(function(e) {
    e.preventDefault();
    number("1")
});
$("#number2").click(function(e) {
    e.preventDefault();
    number("2")
});
$("#number3").click(function(e) {
    e.preventDefault();
    number("3")
});
$("#number4").click(function(e) {
    e.preventDefault();
    number("4")
});
$("#number5").click(function(e) {
    e.preventDefault();
    number("5")
});
$("#number6").click(function(e) {
    e.preventDefault();
    number("6")
});
$("#number7").click(function(e) {
    e.preventDefault();
    number("7")
});
$("#number8").click(function(e) {
    e.preventDefault();
    number("8")
});
$("#number9").click(function(e) {
    e.preventDefault();
    number("9")
});
$("#number0").click(function(e) {
    e.preventDefault();
    number("0")
});
$("#numberB").click(function(e) {
    e.preventDefault();
    numberB()
});
$("#numberC").click(function(e) {
    e.preventDefault();
    numberC()
});

function number(num) {
    var input = getInput(questionList[questionIndex][2]);
    input.text(input.text() + num);
}

function numberB() {
    var input = getInput(questionList[questionIndex][2]);
    var s = input.text();
    input.text(s.substring(0, s.length - 1));
}

function numberC() {
    var input = getInput(questionList[questionIndex][2]);
    input.text("");
}

/**
 * 创建题目
 */
$("button#create").click(function(e) {
    e.preventDefault();
    $("div#creatarea,div#questionarea").toggle();
    // 得到难度和题目
    difficulty = Number($("#creatarea div input[name='select1']:checked").val());
    questionNumber = Number($("#creatarea div input[name='select2']:checked").val());
    createQuestionList(difficulty, questionNumber);
    // 打印消息
    printMessage();
    showProgressBar()
    nextQuestion();
});

function printMessage() {
    $("#messagearea").html("用时<strong>{0}</strong>秒,一共有<strong>{1}</strong>道题, 还剩<strong>{2}</strong>道题,<br> 答对<strong class='ght-success'>{3}</strong>道题,做错<strong class='ght-errors'>{4}</strong>道题!"
        .format(getTime(), questionList.length, questionList.length - success, success, errors));
}

/**
 * 血量
 */
function showProgressBar() {
    var progressBar = $("#progressBar");
    progressBar.css({ "width": 100 - success / questionList.length * 100 + "%" });
    progressBar.text(questionList.length - success);
}

$(document).keyup(function(e) {
    e.preventDefault();
    if ($("#questionarea").is(':visible')) {
        if (e.keyCode == 13) {
            // 回车
            pushAnswer();
        } else if (e.keyCode == 8) {
            // 退格
            numberB();
        } else if (e.keyCode == 48) {
            // 0
            number("0");
        } else if (e.keyCode == 49) {
            // 1
            number("1");
        } else if (e.keyCode == 50) {
            // 2
            number("2");
        } else if (e.keyCode == 51) {
            // 3
            number("3");
        } else if (e.keyCode == 52) {
            // 4
            number("4");
        } else if (e.keyCode == 53) {
            // 5
            number("5");
        } else if (e.keyCode == 54) {
            // 6
            number("6");
        } else if (e.keyCode == 55) {
            // 7
            number("7");
        } else if (e.keyCode == 56) {
            // 8
            number("8");
        } else if (e.keyCode == 57) {
            // 9
            number("9");
        }
    }
});

$("button#submitAnswers").click(function(e) {
    e.preventDefault();
    pushAnswer();
});


function pushAnswer() {
    console.log("提交了答案!");
    console.log(questionList, questionIndex);
    // 得到题目
    var question = questionList[questionIndex];
    console.log(question);
    // 得到的输入的答案
    var userAnswer = Number(getUserAnswer(question[2]));
    var answer = Number(getAnswer(question));
    // 答对了吗
    if (userAnswer === answer) {
        console.log("回答对了: ", userAnswer, answer);
        $("#successAndError").removeClass("ght-errors").addClass("ght-success").text("答对了!!!").show().fadeOut(1000);
        success++;
    } else {
        // 添加一道题目
        questionList.push(createQuestionOne(difficulty));
        question[4]++;
        errors++;
        console.log("回答错了: ", userAnswer, answer);
        $("#successAndError").removeClass("ght-success").addClass("ght-errors").text("答错了!!!").show().fadeOut(1000);
    }
    calculated++;

    printMessage();
    showProgressBar();
    // 下一道题
    nextQuestion();
}

function nextQuestion() {
    questionIndex++;
    if (questionIndex >= questionList.length) {
        questionIndex = 0;
    }
    var haveQuestion = false;
    for (; questionIndex < questionList.length; questionIndex++) {
        if (questionList[questionIndex][3] == questionList[questionIndex][4]) {
            haveQuestion = true;
            break;
        }
    }
    if (haveQuestion) {
        var q = questionList[questionIndex];
        q[3]++;
        createQuestion(q);
    } else {
        console.log("结束了");
        init();
    }
}

function getTime() {
    console.debug('=>%s,%s , %s', 'getTime', Date.parse(new Date()), startTime);
    return (Date.parse(new Date()) - startTime) / 1000;
}

/**
 * 初始化, 打开难度选择, 关闭出题区
 */
function init() {
    $("#creatarea").show();
    $("#questionarea").hide();
    startTime = Date.parse(new Date());

    questionIndex = 0;
    initScore();
    // 读取本地文件..
}

/**
 * 初始化分数
 */
function initScore() {

    questionList = []
    success = 0;
    errors = 0;
    calculated = 0;
}

/**
 * 
 * @param {number} difficulty 
 * @param {number} questionNumber 
 */
function createQuestionList(difficulty, questionNumber) {
    initScore();
    console.log(difficulty, questionNumber);
    for (var x = 0; x < questionNumber; x++) {
        questionList.push(createQuestionOne(difficulty))
    }
}

/**
 * 生成1道题
 * @param {number} questionNumber 
 * @returns
 */
function createQuestionOne(difficulty) {
    // 根据难度得到数字1 和 数字2
    var num1 = getRandomNum(1, difficulty);
    var num2 = getRandomNum(1, difficulty);
    var swap;
    if (num1 < num2) {
        swap = num2;
        num2 = num1;
        num1 = swap;
    }
    // 题目的类型
    var type = getRandomNum(1, 6);

    // var question = createQuestion(num1, num2, type);
    // $("#questionarea").append(question).append("<br>")
    // console.log(num1, num2, type, question);
    return [num1, num2, type, 0, 0]
}

/**
 * 得到有效输入框
 * 
 * @param {number} type 
 * @returns 
 */
function getInput(type) {
    if (type == 1 || type == 4) {
        return $("#input" + 5);
    } else if (type == 2 || type == 5) {
        return $("#input" + 3);
    } else if (type == 3 || type == 6) {
        return $("#input" + 1);
    } else {
        log.error("报错了!        ")
    }
}

/**
 * 展示题目
 * @param {number} num1 
 * @param {number} num2 
 * @param {number} type 
 * @returns
 */
function createQuestion([num1, num2, type, count, error]) {
    console.log([num1, num2, type, count, error]);
    if (type == 1) {
        showQuestion(num2, "+", (num1 - num2), "=", null, 5);
        return num2 + " + " + (num1 - num2) + " = ?";
    } else if (type == 2) {
        showQuestion(num2, "+", null, "=", num1, 3);
        return num2 + " + " + " ? " + " = " + num1;
    } else if (type == 3) {
        showQuestion(null, "+", num2, "=", num1, 1);
        return "? + " + num2 + " = " + num1;
    } else if (type == 4) {
        showQuestion(num1, "-", num2, "=", null, 5);
        return num1 + " - " + num2 + " = ?";
    } else if (type == 5) {
        showQuestion(num1, "-", null, "=", num2, 3);
        return num1 + " - " + " ? " + " = " + num2;
    } else if (type == 6) {
        showQuestion(null, "-", (num1 - num2), "=", num2, 1);
        return "? - " + (num1 - num2) + " = " + num2;
    } else if (type == 7) {
        return num2 + " ? " + (num1 - num2) + " = " + num1;
    } else {
        return num1 + " ? " + (num1 - num2) + " = " + num2;
    }
}

/**
 * 
 * @param {string} t1 
 * @param {string} t2 
 * @param {string} t3 
 * @param {string} t4 
 * @param {string} t5 
 * @param {number} i 第几个可编辑
 */
function showQuestion(t1, t2, t3, t4, t5, i) {
    var i1 = $("#input1");
    i1.text(t1);
    if (i != 1) {
        i1.removeClass("ght-answer");
    } else {
        i1.addClass("ght-answer");
    }
    var i2 = $("#input2");
    i2.text(t2);
    if (i != 2) {
        i2.removeClass("ght-answer");
    } else {
        i2.addClass("ght-answer");
    }
    var i3 = $("#input3");
    i3.text(t3);
    if (i != 3) {
        i3.removeClass("ght-answer");
    } else {
        i3.addClass("ght-answer");
    }
    var i4 = $("#input4");
    i4.text(t4);
    if (i != 4) {
        i4.removeClass("ght-answer");
    } else {
        i4.addClass("ght-answer");
    }
    var i5 = $("#input5");
    i5.text(t5);
    if (i != 5) {
        i5.removeClass("ght-answer");
    } else {
        i5.addClass("ght-answer");
    }
}

/**
 * 
 * @param {number} num1 
 * @param {number} num2 
 * @param {number} type 
 * @returns
 */
function getAnswer([num1, num2, type, count, error]) {
    if (type == 1 || type == 6) {
        return num1;
    } else if (type == 2 || type == 3 || type == 4 || type == 5) {
        return num1 - num2;
    } else if (type == 7) {
        return "+";
    } else {
        return "-";
    }
}


/**
 * 获取用户输入的答案
 * @param {number} type 
 * @returns
 */
function getUserAnswer(type) {
    if (type == 1) {
        return $("#input5").text();
    } else if (type == 2) {
        return $("#input3").text();
    } else if (type == 3) {
        return $("#input1").text();
    } else if (type == 4) {
        return $("#input5").text();
    } else if (type == 5) {
        return $("#input3").text();
    } else if (type == 6) {
        return $("#input1").text();
    } else if (type == 7) {
        return "+";
    } else {
        return "-";
    }
}

/**
 * 随机函数 生成最小值(包含)到最大值(包含)
 * @param {number} Min
 * @param {number} Max
 * @returns
 */
function getRandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return (Min + Math.round(Rand * Range));
}

String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof(args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        } else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

/**
 * 想法: 
 * 选择难度, 包括 10以内加减法, 20以内加减法, 100以内加减法
 * 选择题目数量  10题,  30题,  50题
 * 
 * 根据难度, 生成1个随机数字, 然后在随机一个数字作为加数
 * 随机生成题目的样式, 题目可以有以下样式:
 * 1. 1+1=?  
 * 2. 1+?=2
 * 3. ?+1=2
 * 4. 1-1=?
 * 5. 1-?=0
 * 6. ?-1=0
 * 7. 1?1=2 // 废弃
 * 8. 1?1=0 // 废弃
 * 
 * 题目保存的格式为 [数字1,数字2,题目样式,出现次数,错误次数]
 * 
 * 可以保存在本地cookie中, key = 难度_数字1_数字2_题目样式 value = 题目保存样式
 * 
 * 可以从错题库中随机取题来做
 */